package com.laker.admin.module.inv.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import com.laker.admin.module.inv.mapper.InvMessageMapper;
import com.laker.admin.module.inv.vo.InvStatisticsVo;
import org.springframework.web.bind.annotation.RequestMapping;
import com.laker.admin.module.inv.entity.InvMessage;
import com.laker.admin.module.inv.service.IInvMessageService;
import org.springframework.web.bind.annotation.RestController;
import com.laker.admin.framework.model.Response;
import com.laker.admin.framework.model.PageResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author laker
 * @since 2024-03-21
 */
@RestController
@RequestMapping("/inv/message")
public class InvMessageController {
    @Autowired
    IInvMessageService invMessageService;

    @Autowired
    InvMessageMapper invMessageMapper;

    @GetMapping
    @ApiOperation(value = "分页查询")
    public PageResponse pageAll(@RequestParam(required = false, defaultValue = "1") long page,
                                @RequestParam(required = false, defaultValue = "10") long limit,
                                String keyWord,
                                boolean isDisplay) {
        Page roadPage = new Page<>(page, limit);
        LambdaQueryWrapper<InvMessage> queryWrapper = new QueryWrapper().lambda();

        Integer invSum = isDisplay ? 0 : 1;

        queryWrapper.eq(InvMessage::getDelFlag, 0).and(StrUtil.isNotBlank(keyWord), i -> i.
                like(StrUtil.isNotBlank(keyWord), InvMessage::getCommName, keyWord)
                .or().like(StrUtil.isNotBlank(keyWord), InvMessage::getCommName, keyWord))
                .ge(InvMessage::getInvSum, invSum);

        Page pageList = invMessageService.page(roadPage, queryWrapper);
        return PageResponse.ok(pageList.getRecords(), pageList.getTotal());
    }

    @GetMapping("/getAll")
    @ApiOperation(value = "下载")
    public Response getAll(HttpServletResponse httpServletResponse,
                           String keyWord, String isDisplay, String tempCheckData) {
        LambdaQueryWrapper<InvMessage> queryWrapper = new QueryWrapper().lambda();

        Integer invSum = "on".equalsIgnoreCase(isDisplay) ? 0 : 1;

        queryWrapper.eq(InvMessage::getDelFlag, 0).and(StrUtil.isNotBlank(keyWord), i -> i.
                like(StrUtil.isNotBlank(keyWord), InvMessage::getCommName, keyWord)
                .or().like(StrUtil.isNotBlank(keyWord), InvMessage::getCommName, keyWord))
                .ge(InvMessage::getInvSum, invSum)
                .in(StrUtil.isNotBlank(tempCheckData), InvMessage::getInvId, new ArrayList<>(Arrays.asList(tempCheckData.split(","))));

        String fileName = invMessageService.getAll(queryWrapper);
        return PageResponse.ok(fileName);
    }

    @PostMapping
    @ApiOperation(value = "新增或者更新")
    public Response saveOrUpdate(@RequestBody InvMessage param) {
        return Response.ok(invMessageService.saveOrUpdate(param));
    }

    @PostMapping("/tradein")
    @ApiOperation(value = "入库")
    public Response tradein(@RequestBody InvMessage param) {
        if (param.getTransSum() <= 0) {
            return Response.error("500", "入库数量必须大于0");
        }

        return Response.ok(invMessageService.tradein(param));
    }

    @PostMapping("/tradeout")
    @ApiOperation(value = "消耗")
    public Response tradeout(@RequestBody InvMessage param) {
        if (param.getTransSum() <= 0) {
            return Response.error("500", "消耗数量必须大于0");
        }

        InvMessage tmp = invMessageService.getById(param.getInvId());
        if (param.getTransSum() > tmp.getInvSum()) {
            return Response.error("500", "消耗数量不允许大于总库存");
        }

        return Response.ok(invMessageService.tradeout(param));
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询")
    public Response get(@PathVariable Long id) {
        return Response.ok(invMessageService.getById(id));
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除")
    public Response delete(@PathVariable Long id) {
        return Response.ok(invMessageService.removeById(id));
    }

    @DeleteMapping("/batch/{ids}")
    @ApiOperation(value = "根据批量删除ids删除")
    public Response batchRemove(@PathVariable Long[] ids) {
        return Response.ok(invMessageService.removeByIds(CollUtil.toList(ids)));
    }

    @GetMapping("/console")
    public Response console() {
        int inv = invMessageService.invAllCount();
        int tin = invMessageService.tradeinAllCount();
        int tout = invMessageService.tradeoutAllCount();
        int per = invMessageService.tradeoutPersonCount();

        Dict res = Dict.create().set("inv", inv)
                .set("tin", tin)
                .set("tout", tout)
                .set("per", per);
        return Response.ok(res);
    }

    @GetMapping("/realtimeinv")
    @ApiOperation(value = "实时库存")
    public Response realtimeinv() {
        List<InvStatisticsVo> invStatisticsVo = invMessageMapper.selectRealtimeInv();
        return Response.ok(invStatisticsVo);
    }

    @GetMapping("/tradeoutinv")
    @ApiOperation(value = "消耗流水")
    public Response tradeoutinv() {
        List<InvStatisticsVo> outStatisticsVo = invMessageMapper.selectTradeoutInv();
        return Response.ok(outStatisticsVo);
    }
}
